package graduationorder.graduationorder.Interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import graduationorder.graduationorder.error.BusinessException;
import graduationorder.graduationorder.error.EmBusinessException;
import graduationorder.graduationorder.util.JWTUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Mzk
 * @version 1.0
 * @description: 用户是否登录拦截器
 * @date 2024/8/3 下午 4:38
 */
@Component
public class UserLoginAuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        try {
            JWTUtils.verify(token);
            return true;
        } catch (TokenExpiredException e) {
            throw new BusinessException(EmBusinessException.USER_AUTHORIZATION_EXCEPTION.setErrorMsg("Token已经过期!!!"));
        } catch (SignatureVerificationException e){
            throw new BusinessException(EmBusinessException.USER_AUTHORIZATION_EXCEPTION.setErrorMsg("签名错误!!!"));
        } catch (AlgorithmMismatchException e){
            throw new BusinessException(EmBusinessException.USER_AUTHORIZATION_EXCEPTION.setErrorMsg("加密算法不匹配!!!"));
        } catch (Exception e) {
            throw new BusinessException(EmBusinessException.USER_AUTHORIZATION_EXCEPTION.setErrorMsg("无效token~~"));
        }
    }
}
